#include<stdio.h>
#include<conio.h>
#include<graphics.h>

int main()
{
	float width, height;
	width = 600;
	height = 400;
	
	initgraph(width, height);//设置窗口大小

	float radius, ball_x, ball_y;
	float ball_vy, gravity;

	radius = 10;//小球半径
	ball_x = width / 4;//小球x轴坐标
	ball_y =  height/2;//小球初始y轴坐标
	ball_vy = 0;//小球初速度
	gravity = 0.4;//小球重力加速度


	float rect_left_x, rect_top_y, rect_width, rect_height;
	float rect_vx;
	rect_height = 100;
	rect_width = 20;
	rect_left_x = width * 3 / 4;
	rect_top_y = height - rect_height;
	rect_vx = -2;                                         //添加下面的障碍物

	float rect_left_x2, rect_top_y2, rect_width2, rect_height2;
	float rect_vx2;
	rect_height2 = 200;
	rect_width2 = 20;
	rect_left_x2 = width * 3 / 4;;
	rect_top_y2 = 0;
	rect_vx2= -2;                        //添加上面的障碍物


	int score = 0;
	int isBallonFloor = 1;

	while (1) {
		if (_kbhit()) {
			char input = _getch();
			if (input== ' '&& isBallonFloor==1) {
				ball_vy = -10; 
				isBallonFloor = 0;
			}

		}

		ball_vy = ball_vy + gravity;
		ball_y = ball_y + ball_vy;

		
		isBallonFloor = 1;

		
		rect_left_x = rect_left_x + rect_vx;
		if (rect_left_x <= 0) {                 //如果方块跑到最左边
			score++;
			rect_left_x = width; //在最右边重新出现
			rect_height = rand() % int(height / 4) + height / 4;//设置方块随机高度
			rect_vx = rand() / float(RAND_MAX) * 4 - 7;//设置方块随机速度
		}//下面的障碍物向左移动

		rect_left_x2 = rect_left_x2 + rect_vx2;
		if (rect_left_x2 <= 0) {                 //如果方块跑到最左边
			score++;
			rect_left_x2 = width; //在最右边重新出现
			rect_height2 = rect_height +150;//设置方块随机高度
			rect_vx2 = rand() / float(RAND_MAX) * 4 - 7;//设置方块随机速度
		}//上面的障碍物向左移动

		if ((rect_left_x <= ball_x + radius) && (rect_left_x + rect_width >= ball_x - radius) && (height - rect_height <= ball_y + radius)) {
			score = 0;
			Sleep(35);
		}
		 
		if ((rect_left_x2 <= ball_x + radius) && (rect_left_x2 + rect_width2 >= ball_x - radius)&& (height - rect_height2 >= ball_y - radius)) {
			score = 0;
			Sleep(35);
		}

		
		cleardevice();//清空画面

		fillrectangle(rect_left_x, height - rect_height, rect_left_x + rect_width, height);//绘制上面的障碍物
		fillrectangle(rect_left_x2,0 , rect_left_x2 + rect_width2, height-rect_height2);//绘制下面的障碍物
		fillcircle(ball_x, ball_y, radius);//绘制小球

		TCHAR s[20];//定义字符串数组
		swprintf_s(s, _T("%d"), score);//将score转换为字符串
		settextstyle(40, 0, _T("宋体"));//设置文字大小、字体
		outtextxy(50, 40, s);//输出得分文字
		Sleep(10);//暂停10ms

	}


	
	_getch();
	closegraph();

	return 0;
}